/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package server;

import java.sql.SQLException;

public class Main
{
	/* OpCode Client:
	 * 0x00 - chat message
	 * 0x01 - ClientControlShutdown
	 * 0x02 - Nickname
	 * 
	 * OpCode Daemon:
	 * 0x03 - SystemControlRestart
	 * 0x04 - SystemControlShutdown
	 * 0x05 - Password
	 * 0x06 - DaemonLoginFail
	 * 
	 * 0x07 - client list update
	 * 0x08 - private msg
	 * 0x09 - udrzovaci packet
	*/
	private static Server server = null; // Promenna pro ovladani serveru
	private static Daemon daemon = null; // Promenna pro ovladani daemonu

	public static void main(String[] args)
	{
		Sifrovani.generatePhrase(); // Vygenerovani sifrovaci fraze
		
		try
		{
			Mysql.getInstance(); // Inicializace c3p0 modulu pro komunikaci s mysql
			server = new Server(); // Vytvoreni nove instance Serveru
			server.start(); // Zapnuti vlakna serveru
			daemon = new Daemon(); //Vytvoreni nove instance daemonu
			daemon.start(); //Zapnuti vlakna daemonu
			System.out.println("Server started.");
		}
		catch (SQLException e)
		{
			// Pokud inicializace MySQL selze je vyhozena vyjimka a program ukoncen
			e.printStackTrace();
			System.exit(-1);
		}
	}

	// Metoda pro restartovani/vypnuti serveru
	public static void restart(boolean restart)
	{
		if (restart)
		{
			System.out.print("Restarting server: ");
			if (server != null)
				server.shutdown(); // Interni metoda serveru odpoji uzivatele vypne server 
			server = new Server(); // Nova instance serveru
			server.start(); // Zapnuti vlakna
			if (daemon != null)
				daemon.shutdown(); // Interni metoda daemonu odpoji uzivatele vypne server 
			daemon = new Daemon(); // Nova instance daemonu
			daemon.start(); // Zapnuti vlakna
			Sifrovani.generatePhrase(); // Vygenerovani nove sifrovaci fraze
			System.out.println("Done"); 
		}
		else
		{
			System.out.println("Shutting down server.");
			server.shutdown(); // Vypnuti serveru
			daemon.shutdown(); // Vypnuti daemonu
			System.exit(0); // Vypnuti aplikace
		}
	}
}
